﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MVCSoict.Models;
using Newtonsoft.Json;

namespace MVCSoict.Controllers
{
    public class TitleController : Controller
    {
        private staffsoictEntities1 db = new staffsoictEntities1();
        private JsonSerializerSettings jsonSettings = new JsonSerializerSettings()
        {
            PreserveReferencesHandling = PreserveReferencesHandling.Objects
        };
        // GET: /Title/
        public ActionResult Index()
        {
            return View(db.Titles.ToList());
        }

        public string Select(string keyword, int page, int pagesize)
        {
            string jsonResult = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "title_select"))
                {
                    using (var context = new staffsoictEntities1())
                    {
                        var titles = from t in context.Titles
                                     where t.title1.Contains(keyword)
                                     orderby t.tid
                                     select t;

                        var pageData = titles.Skip((page - 1) * pagesize).Take(pagesize).ToList();
                        foreach (var titl in pageData)
                        {
                            jsonResult += JsonConvert.SerializeObject(titl, jsonSettings);
                        }
                    }
                }
            }
            return jsonResult;
        }

        public string Add([Bind(Include = "title1")] Title title) 
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "title_add"))
                {
                    try
                    {
                        title.tid = GetNextId();
                        db.Titles.Add(title);
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(title, jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        public int GetNextId() 
        {
            int res = 0;
            var titles = from t in db.Titles
                         orderby t.tid
                         select t;
            int count = titles.Count();
            if (count > 0)
            {
                res = titles.ToList()[count - 1].tid + 1;
            }
            return res;
        }

        public string Xoa(int? id) 
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "title_xoa"))
                {
                    Title title = db.Titles.Find(id);
                    try
                    {
                        db.Titles.Remove(title);
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(title);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        //test
        public string Update([Bind(Include = "tid,title1")] Title title)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "title_update"))
                {
                    try
                    {
                        db.Entry(title).State = EntityState.Modified;
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(title, jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        public string Get(int id)
        {
            string res = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "title_get"))
                {
                    try
                    {
                        var titles = from t in db.Titles
                                     where t.tid.Equals(id)
                                     select t;
                        if ((titles.ToList<Title>().Count() > 0))
                            res = JsonConvert.SerializeObject(titles.ToList<Title>()[0], jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        // GET: /Title/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Title title = db.Titles.Find(id);
            if (title == null)
            {
                return HttpNotFound();
            }
            return View(title);
        }

        // GET: /Title/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Title/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include="tid,title1")] Title title)
        {
            if (ModelState.IsValid)
            {
                db.Titles.Add(title);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(title);
        }

        // GET: /Title/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Title title = db.Titles.Find(id);
            if (title == null)
            {
                return HttpNotFound();
            }
            return View(title);
        }

        // POST: /Title/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include="tid,title1")] Title title)
        {
            if (ModelState.IsValid)
            {
                db.Entry(title).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(title);
        }

        // GET: /Title/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Title title = db.Titles.Find(id);
            if (title == null)
            {
                return HttpNotFound();
            }
            return View(title);
        }

        // POST: /Title/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Title title = db.Titles.Find(id);
            db.Titles.Remove(title);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
